#import "Chapter.h"
#import "NSString+HTML.h"

@implementation Chapter 

@synthesize delegate, chapterIndex, title, pageCount, spinePath, windowSize, fontPercentSize;

- (id) initWithPath:(NSString*)theSpinePath title:(NSString*)theTitle chapterIndex:(int) theIndex{
    if((self=[super init])){
        spinePath = [theSpinePath retain];
        title = [theTitle retain];
        chapterIndex = theIndex;
    }
    return self;
}

- (void) loadChapterWithWindowSize:(CGRect)theWindowSize fontPercentSize:(int) theFontPercentSize{
    fontPercentSize = theFontPercentSize;
    windowSize = theWindowSize;

    UIWebView* webView = [[UIWebView alloc] initWithFrame:windowSize];
    [webView setDelegate:self];

    NSURLRequest* urlRequest = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:spinePath]];
    [webView loadRequest:urlRequest];
}

- (void) webViewDidFinishLoad:(UIWebView*)webView {
    [webView stringByEvaluatingJavaScriptFromString:[[NSString alloc] initWithContentsOfURL:(kAppDelegate).createCssRule encoding:NSUTF8StringEncoding error:nil]];

    NSString *fontName = [kAppDelegate fontFamilyNameWithType:[[(kAppDelegate).generalSetting objectForKey:FontFace] intValue]];

	NSString *insertRule1 = [NSString stringWithFormat:@"addCSSRule('html', 'margin: 0px; padding: %fpx %fpx %fpx %fpx; height: %fpx; -webkit-column-gap: %fpx; -webkit-column-width: %fpx;')", Top_Padding_Viewer, Left_Padding_Viewer, 0.0f, Left_Padding_Viewer, webView.frame.size.height - (Top_Padding_Viewer) - (Height_Banner), 2*(Left_Padding_Viewer), webView.frame.size.width];
	NSString *insertRule2 = [NSString stringWithFormat:@"addCSSRule('p', 'text-align: justify;')"];
    NSString *insertRule3 = @"addCSSRule('img', 'height: auto; width: auto; max-width: 100%; max-height: 100%; border: none;')";
	NSString *setTextSizeRule = [NSString stringWithFormat:@"addCSSRule('body', 'font-weight: normal; font-family: %@; font-size: %dpx;')", fontName, fontPercentSize];

	[webView stringByEvaluatingJavaScriptFromString:insertRule1];
	[webView stringByEvaluatingJavaScriptFromString:insertRule2];
    [webView stringByEvaluatingJavaScriptFromString:insertRule3];
    [webView stringByEvaluatingJavaScriptFromString:setTextSizeRule];

	int totalWidth = [[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollWidth"] intValue];
	pageCount = (int)((float)totalWidth/webView.bounds.size.width);

    [webView release];
    if ([delegate respondsToSelector:@selector(chapterDidFinishLoad:)]) {
        [delegate chapterDidFinishLoad:self];
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"%@", error);
	[webView release];
}

- (void)dealloc {
    [title release];
	[spinePath release];
    [super dealloc];
}

@end
